package com.shuai.baibi.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.shuai.baibi.common.ErrorCode;
import com.shuai.baibi.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 将用户上传的excel文件转换成字符串
 */
@Slf4j
public class ExcelHandleUtils {
    public static String handleExcelToStr(MultipartFile file) {
        List<Map<Integer, String>> dataList = null  ;
        try {
            dataList = EasyExcel.read(file.getInputStream())
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet()
                    .headRowNumber(0)
                    .doReadSync();
        } catch (IOException e) {
            log.error("读取excel文件出错");
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "读取excel文件出错");
        }
        if (dataList == null || dataList.size() == 0) {
            return null;
        }
        StringBuilder csvStr = new StringBuilder();
        // 获取表头数据
        List<String> headerData = dataList.get(0).values().stream().filter(StringUtils::isNotEmpty).collect(Collectors.toList());
        csvStr.append(StringUtils.join(headerData, ","));
        csvStr.append("\n");

        // 读取表体数据
        for (int i = 1; i < dataList.size(); i++) {
            Map<Integer, String> dataItem = dataList.get(i);
            List<String> dataItemHandled = dataItem.values().stream().filter(StringUtils::isNotEmpty).collect(Collectors.toList());
            csvStr.append(StringUtils.join(dataItemHandled, ","));
            csvStr.append("\n");
        }
        return csvStr.toString();
    }
}
